<?php

namespace app\api\controller;

use app\api\validate\UserValidate;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Attention;
use app\common\model\BrowsingHistory;
use app\common\model\Config;
use app\common\model\FamilyTree;
use app\common\model\FollowFriend;
use app\common\model\GiveLog;
use app\common\model\GxHistory;
use app\common\model\Remind;
use app\common\model\Room;
use app\common\model\RoomApply;
use app\common\model\RoomUser;
use app\common\model\User as UserModel;
use app\common\model\Vote;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    //protected $noNeedLogin = '*';
    protected $noNeedLogin = ['editPwd'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 用户基础信息查询
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        $user = UserModel::field('id,nickname,mobile,avatar,level,gender,birthday,money,score,reward,status,invite_code,parent,bio,education,seniority,province,city,area,address,identity')->find($this->auth->id);
        $user->share_gx = Config::getValue('register_jl_gxz','family_tree');
        $user->child_count = UserModel::where('parent',$this->auth->id)->count();
        $this->success('请求成功',$user);
    }

    /**
     * 通讯录查询 族谱与家谱
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGenealogyUserList(){
        $types = request()->post('types',1);
        $name = request()->post('name');
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));

        //$post = request()->post();
        //$validate = new Validate([
        //    'lng'   => 'require',
        //    'lat'   => 'require'
        //],[
        //    'lng'   => '定位失败',
        //    'lat'   => '定位失败'
        //],[]);
        //
        //if(!$validate->check($post)){
        //    $this->error($validate->getError());
        //}
        $roomId = RoomUser::getRoomIdByTypes($this->auth->id,$types);
        if(empty($roomId)){
            $this->success('请求成功',[],2);
        }
        $userIds = RoomUser::getUserIds($roomId);
        //$userIds = array_merge(array_diff($userIds, [$this->auth->id]));
        $userIds = array_diff($userIds, [$this->auth->id]);
        if(!empty($name)){
            $user = UserModel::where('id','IN',$userIds)->where('nickname','like','%'. $name .'%')->field('id,nickname,avatar,level,seniority,bio,lat,lng,education')->select();
        }else{
            $user = UserModel::where('id','IN',$userIds)->page($page,$limit)->field('id,nickname,avatar,level,seniority,bio,lat,lng,education')->select();
        }
        foreach($user as $v){

            //$distance = UserModel::getDistance([$post['lng'],$post['lat']],[$v['lng'],$v['lat']]);
            //if($distance < 1){
            //    $v->distance = floor($distance * 1000) . '米';
            //}else{
            //    $v->distance = $distance . '公里';
            //}
            $v->status = RoomUser::where('user_id',$v['id'])->where('room_id',$roomId)->value('status');
            //$v->distance = UserModel::getDistance($post['lat'],$post['lng'],$v['lat'],$v['lng']);
        }
        if($types == 1){
            \app\common\model\Task::complete(1,$this->auth->id);
        }
        $zuzhangId = Room::where('id',$roomId)->value('user_id');
        $roomApplyCount = RoomApply::where('room_id',$roomId)->where('status',0)->count();
        $this->success(['zuzhang_id'=>$zuzhangId,'room_apply_count'=>$roomApplyCount],$user);
    }

    /**
     * 查询家族列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFamilyList(){
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));
        $seniority = request()->post('seniority');
        $name = request()->post('name');
        $query = Room::with('levelInfo')->where('types',2);
        if(!empty($seniority)){
            // 按辈分查
            $query = $query->where('FIND_IN_SET(:id,seniority)',['id' => $seniority]);
        }
        if(!empty($name)){
            // 按用户名查
            $userIds = UserModel::where('nickname','like','%'. $name .'%')->column('id');
            if(empty($userIds)){
                $query = $query->where('id',1);
            }else{
                $roomIds = RoomUser::where('user_id','IN',$userIds)->column('room_id');
                $query = $query->where('id','IN',$roomIds);
            }
        }
        $list = $query->page($page,$limit)->order('user_count','desc')->field('id,name,image,level,created_at,user_count')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 修改密码
     */
    public function editPwd(){
        $post = request()->post();
        if(!isset($post['type']) || empty($post['type']) || !in_array($post['type'],[1,2])){
            $this->error('参数错误');
        }
        $rule = [
            'code'      => 'require',
            'mobile'    => 'require'
        ];
        if($post['type'] == 1){
            $rule['password'] = 'require';
            $event = 'editLoginPwd';
            $field = 'password';
        }else{
            $rule['password'] = 'require';
            $event = 'editPayPwd';
            $field = 'pay_password';
        }
        $validate = new Validate($rule,[],[
            'password'  =>'密码',
            'code'      =>'验证码',
            'mobile'    =>'手机号',
        ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $ret = Sms::check($post['mobile'], $post['code'], $event);
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $sale = UserModel::where('mobile',$post['mobile'])->value('salt');
        $password = $this->auth->getEncryptPassword($post['password'],$sale);
        if($this->auth->id){
            $userId = $this->auth->id;
        }else{
            $userId = UserModel::where('mobile',$post['mobile'])->value('id');
        }
        $result = UserModel::update([$field=>$password],['id'=>$userId]);
        if($result === false){
            $this->error('修改失败，请稍后重试');
        }
        $this->success('修改成功');
    }

    /**
     * 修改会员个人信息
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     * @param string $gender   性别
     */
    public function profile()
    {
        $post = request()->post();
        $post['avatar'] = trim($post['avatar']) == 'null' ? '' : trim($post['avatar']);
        $post['gender'] = trim($post['gender']) == 'null' ? '' : trim($post['gender']);
        $post['birthday'] = trim($post['birthday']) == 'null' ? date('Y-m-d') : trim($post['birthday']);
        $post['education'] = trim($post['education']) == 'null' ? '' : trim($post['education']);
        $post['seniority'] = trim($post['seniority']) == 'null' ? '' : trim($post['seniority']);
        $post['bio'] = trim($post['bio']) == 'null' ? '' : trim($post['bio']);
        $post['identity'] = trim($post['identity']) == 'null' ? '' : trim($post['identity']);
        $post['province'] = trim($post['province']) == 'null' ? '' : trim($post['province']);
        $post['city'] = trim($post['city']) == 'null' ? '' : trim($post['city']);
        $post['area'] = trim($post['area']) == 'null' ? '' : trim($post['area']);
        $post['address'] = trim($post['address']) == 'null' ? '' : trim($post['address']);
        $validate = new UserValidate();
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $user_id = $this->auth->id;

        $updateData = [
            'avatar'    => $post['avatar'],
            'gender'    => $post['gender'],
            'birthday'  => $post['birthday'],
            'education' => $post['education'],
            'seniority' => $post['seniority'],
            'bio'       => $post['bio'],
            'identity'  => $post['identity'],
            'province'  => $post['province'],
            'city'      => $post['city'],
            'area'      => $post['area'],
            'address'   => $post['address'],
        ];
        //$province = Area::where('id',$post['province'])->where('level',1)->value('name');
        //$city = Area::where('id',$post['city'])->where('level',2)->value('name');
        //$area = Area::where('id',$post['area'])->where('level',3)->value('name');
        //if(empty($province) || empty($city) || empty($area)){
        //    $this->error('地址选择错误');
        //}
        //$result = getLatLng($post['province'].$post['city'].$post['area'].$post['address'],$post['city']);
        //if(empty($result)){
        //    $this->error('获取位置失败');
        //}
        //$updateData['lat'] = $result['lat'];
        //$updateData['lng'] = $result['lng'];
        FamilyTree::where('user_id',$this->auth->id)->update([
            'seniority'     => $post['seniority'],
            'gender'        => $post['gender'],
            'start_time'    => $post['birthday'],
            'province'      => $post['province'],
            'city'          => $post['city'],
            'area'          => $post['area'],
            'address'       => $post['address'],
        ]);
        UserModel::where('id',$user_id)->update($updateData);
        $this->success('修改成功');
    }

    /**
     *我的贡献值
     */
    public function myGxNum()
    {
        $user_id = $this->auth->id;
        $after_balance = $this->auth->money;
        $amount = $this->auth->score;
        $get_gx_num = GxHistory::where('user_id',$user_id)->where('coin_id','money')->where('amount','>',0)->whereTime('created_at','today')->sum('amount');
        $todayamount = GxHistory::where('user_id',$user_id)->where('coin_id','score')->where('amount','>',0)->whereTime('created_at','today')->sum('amount');
        $monthGxHis = GxHistory::where('user_id',$user_id)->where('coin_id','score')->where('amount','>',0)->whereTime('created_at','month')->sum('amount');
        return $this->success('请求成功',[
            'money'         => $after_balance,
            'score'         => $amount,
            'get_gx_num'    => $get_gx_num,
            'todayamount'   => $todayamount,
            'monthGxHis'    => $monthGxHis,
        ]);
    }

    /**
     * 获取资产列表
     */
    public function getAssetsList(){
        $coinId = request()->post('coin_id');
        $page = request()->post('page',1);
        $limit = request()->post('limit');
        if(empty($coinId) || !in_array($coinId,['money','score'])){
            $this->error('参数错误');
        }
        $list = GxHistory::getList($this->auth->id,$coinId,$page,$limit);
        $this->success('请求成功',$list);
    }

    /**
     * 投票历史
     */
    public function voteHistory(){
        $type = request()->post('type',1);// 类型:1=我的投票,2=给我投票
        $page = request()->post('page',1);
        $limit = request()->post('limit');
        if(empty($type) || !in_array($type,[1,2])){
            $this->error('参数错误');
        }
        $list = Vote::getList($type,$this->auth->id,$page,$limit);
        $this->success('请求成功',$list);
    }


    /**
     * 关注的好友
     */
    public function followFriend()
    {
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));
        $att = Attention::with('toUser')->where('user_id',$this->auth->id)->page($page,$limit)->select();
        return $this->success('请求成功',$att);
    }

    /**
     * 取消关注
     */
    public function noAttention()
    {
        $user_id = $this->auth->id;
        $attuser = $this->request->post('att_user_id');
        if(empty($attuser)){
            $this->error('参数错误');
        }
        $count = Attention::where('user_id',$user_id)->where('att_user_id',$attuser)->count();
        if($count < 1){
            $this->error('参数错误');
        }
        Attention::where('user_id',$user_id)->where('att_user_id',$attuser)->delete();
        return $this->success('已取消');
    }

    /**
     * 提醒列表
     * @param type 1=生日提醒,2=祭祀提醒
     */
    public function remindList(){
        $type = request()->post('type',1);
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));
        if(!in_array($type,[1,2])){
            $this->error('参数错误');
        }

        $userIds = Attention::where('user_id',$this->auth->id)->column('att_user_id');
        if($type == 1){
            $sym = 'IS NULL';
            $list = UserModel::where('id','IN',$userIds)->where('die_time '.$sym)->field('id,nickname,avatar,birthday,die_time,education')->page($page,$limit)->select();
        }else{
            $sym = 'IS NOT NULL';
            $list = UserModel::where('id','IN',$userIds)->where('die_time '.$sym)->field('id,nickname,avatar,birthday,die_time,education')->page($page,$limit)->select();
        }
        $ids = Remind::where('user_id',$this->auth->id)->where('types',$type)->column('to_user_id');
        foreach($list as $v){
            $v->remind_status = in_array($v['id'],$ids) ? 1 : 0;
            $count = GiveLog::where('user_id',$this->auth->id)->where('to_user_id',$v['id'])->where('status',0)->count();
            $v->auto_give = $count > 0 ? 1 : 0;
        }
        $remindUser = UserModel::getRemindUser($this->auth->id,$type);
        $this->success('请求成功',[
            'remind_user'   => $remindUser,
            'list'          => $list
        ]);
    }

    /**
     * 开启/关闭提醒
     * @param type 1=生日提醒,2=祭祀提醒
     */
    public function updateRemind(){
        $type = request()->post('type',1);
        $userId = request()->post('user_id');
        if(empty($userId) || !in_array($type,[1,2])){
            $this->error('参数错误');
        }
        $count = UserModel::where('id',$userId)->count();
        if($count < 1){
            $this->error('参数错误!');
        }
        $info = Remind::where('user_id',$this->auth->id)->where('to_user_id',$userId)->where('types',$type)->find();
        if(empty($info)){
            Remind::create([
                'user_id'   => $this->auth->id,
                'to_user_id'=> $userId,
                'types'     => $type,
            ]);
        }else{
            Remind::destroy($info['id']);
        }
        $this->success('操作成功');
    }

    /**
     * 生日/祭祀 提醒列表
     */
    public function startRemindList(){
        $list = Remind::where('user_id',$this->auth->id)->select();
        $year = date('Y');
        $toDay = date('Y-m-d');
        $sDay = date('Y-m-d',strtotime('+3 day'));
        $remindList = [];
        foreach($list as $k=>$v){
            if($v['types'] == 1){
                $sym = 'IS NULL';
                $field = 'birthday';
            }else{
                $sym = 'IS NOT NULL';
                $field = 'die_time';
            }
            $info = \app\common\model\User::where('id',$v['to_user_id'])->where('die_time '.$sym)->field('id,nickname,avatar,birthday,die_time,DATE_FORMAT('. $field .', "'.$year.'-%m-%d") as format_birthday,education')->having('format_birthday >= "'. $toDay .'" AND format_birthday <= "'. $sDay .'"')->find();
            if(!empty($info)){
                $info['type'] = $v['types'];
                $b = substr($info[$field],8,10);
                $thisB = date('d');
                $info['cha'] = $b - $thisB;
                $remindList[] = $info;
            }
        }
        $this->success('请求成功',$remindList);
    }

    /**
     * 浏览历史
     */
    public function browsingHistory()
    {
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));
        $att = BrowsingHistory::with('message')->where('user_id',$this->auth->id)->page($page,$limit)->select();
        $this->success('请求成功',$att);
    }

    /**
     *删除浏览历史
     */
    public function delHistory()
    {
        $ids = $this->request->post('ids');
        $result = BrowsingHistory::where('user_id',$this->auth->id)->where('id','IN',$ids)->delete();
        if($result){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 礼物记录
     */
    public function giftLog(){
        $type = request()->post('type',1);// 1=我收到的礼物,2=我送出的礼物
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginte.list_rows'));
        if($type == 1){
            $list = GiveLog::with('user')->where('to_user_id',$this->auth->id)->where('status',1)->page($page,$limit)->select();
            $total = GiveLog::where('to_user_id',$this->auth->id)->where('status',1)->count();
            $sumMoney = GiveLog::where('to_user_id',$this->auth->id)->where('status',1)->sum('to_money');
        }else{
            $list = GiveLog::with('toUser')->where('user_id',$this->auth->id)->where('status',1)->page($page,$limit)->select();
            $total = GiveLog::where('user_id',$this->auth->id)->where('status',1)->count();
            $sumMoney = GiveLog::where('user_id',$this->auth->id)->where('status',1)->sum('score');
        }

        $this->success('请求成功',['list'=>$list,'total'=>$total,'sum_money'=>$sumMoney]);
    }

    protected function sign($param){
        ksort($param);
        foreach($param as $k=>$v){
            $param[$k] = urlencode($v);
        }
        $stringParam = http_build_query($param) . '&time=' . time();
        return $stringParam . '&hash=' . strtoupper(md5($stringParam . '&salt=IsCPXV9Sdz41tLcXTqdv7LUQ2gwslJZA'));

    }

    /**
     * 获取配置
     */
    public function getConfig(){
        $post = request()->post();
        $result = $this->validate($post,'ConfigValidate');
        if($result !== true){
            $this->error($result);
        }
        $value = Config::getValue($post['key'],$post['group']);
        return $this->success('请求成功',$value);
    }
}
